package com.lpf.mybatis.mapper;

import com.lpf.mybatis.config.MapperRegistry;
import com.lpf.mybatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 功能描述：返回的代理类内部会调用 MapperProxy.invoke 方法
 */
public class MapperProxy<T> implements InvocationHandler {

    private final SqlSession sqlSession;
    private final Class<T> mappperInterface;

    public MapperProxy(SqlSession gpSqlSession, Class<T> clazz) {
        this.sqlSession = gpSqlSession;
        this.mappperInterface = clazz;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        MapperRegistry.MapperData mapperData = sqlSession
                                                        .getConfiguration()
                                                        .getMapperRegistry()
                                                        .get(method.getDeclaringClass().getName() + "." + method.getName());

        if (mapperData != null) {
            System.out.println(String.format("SQL [ %s ], parameter [%s] ", mapperData.getSql(), args[0]));
            return sqlSession.selectOne(mapperData, String.valueOf(args[0]));
        }

        return null;
    }
}